﻿package com.lin.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;

import com.yunfeng.supercall.bean.Constants;





import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.util.Pair;
import android.widget.Toast;



class IO {
	private static final String TAG = "WONIULU";

	private static final String ACTION_SIGNUP = "/rest/v2/user/inscription";
	private static final String LOGIN = "login";
	private static final String USER = "user";
	private static final String TYPE = "type";
	private static final String PASSWD = "passwd";
	private static final String PASSWORD = "password";
	private static final String USERNAME = "username";

	private static final String ACK = "ack";
	private static final String TOKEN = "token";
	private static final String ID = "id";
	private static final String STATUS = "status";
	private static final String MESSAGE = "message";
	private static final String DATA = "data";

	private boolean mDevMode;
	private String mToken;
	private static final String ITEMS = "items";

	//Need a context to display the toast when no connection
	private Context mContext;
	public static String SERVER_URL = "http://superchat.api.yunfengapp.com:8989/";
	public static String COMMAN_SERVER_URL = "http://superchat.api.yunfengapp.com:8887/Common/ComServer";
	public static String GetShareListNewURL = "http://superchat.api.yunfengapp.com:8989/share/getShareListNew";
	public static String GetShareListNewBase= "http://superchat.api.yunfengapp.com:8989/";
	public static String NORMAL_SERVER_URL = "http://superchat.api.yunfengapp.com:8887/Super/";
	public static String UPLOAD_IMG_URL = "http://superchat.api.yunfengapp.com:8887/Controllers/uploadFile.ashx";
	// stay short on connection, but read is sometime long (s2lo)
	private static final int CONNECTION_TIMEOUT = 10000;
	private static final int READ_TIMEOUT = 60000; //LIN before is 30000 and 5000

	private static final class Param extends Pair<String,String> {
		public Param(String first, String second) {
			 super(first, second);
		}
	}
	private Handler mHandler;
	LocalDb mLocalDb;
	boolean first;

	private Session mSession;
	/*package*/ IO(LocalDb local_db, boolean devmode, Context context) {
		mLocalDb = local_db;
		mDevMode = devmode;
		mContext = context;
		mHandler = new Handler();
		first = true;	
		mSession = Session.getSession();
	}


	/*package*/ 
	JSONObject signup(String email, String password, String nickname) {
		Param[] parameters = buildParameters(ACK, "adduser", LOGIN, email, TYPE, "email", USER, email, PASSWORD, password, USERNAME, nickname);
		JSONObject result;
		try {
			JSONObject data = new JSONObject();
			data.put(ACK, nickname);
			data.put(LOGIN, email);
			data.put(PASSWD, password);
			result = httpGet(parameters);

			if(result != null ) {
				if(result.getInt("status") == 1) {
					JSONObject mDataObject = result.getJSONObject("data");
					mToken = mDataObject.getString("UserCode");
				}
				return result;
			} else {
				return null;
			}


		} catch (JSONException e) {
			// pass: protocol error
			e.printStackTrace();
			return null;
		}
	}

	/*package*/ 
	JSONObject changePass(String json) {
		Param[] parameters = buildParameters("FUNC", "ChangePass", "PARAS", json);
		JSONObject result;
		try {
			result = httpPost(COMMAN_SERVER_URL, parameters, new JSONObject(json));
			return result;
		} catch (JSONException e) {
			// pass: protocol error
			e.printStackTrace();
			return null;
		}
	}






	/*package*/ 
	JSONObject checkLocalAddressBook(String json) {
		Param[] parameters = buildParameters("FUNC", "CheckLocalAddressBook", "PARAS", json);
		JSONObject result;
		try {
			result = httpPost(COMMAN_SERVER_URL, parameters, new JSONObject(json));

			return result;

		} catch (JSONException e) {
			// pass: protocol error
			e.printStackTrace();
			return null;
		}
	}


	/*package*/ 
	JSONObject getNoGroupFriendList(String json) {
		Param[] parameters = buildParameters("FUNC", "GetNoGroupFriendList", "PARAS", json);
		JSONObject result;
		try {
			result = httpPost(COMMAN_SERVER_URL, parameters, new JSONObject(json));

			return result;

		} catch (JSONException e) {
			// pass: protocol error
			e.printStackTrace();
			return null;
		}
	}

	/*package*/ 
	JSONObject searchUser(String json) {
		Param[] parameters = buildParameters("FUNC", "SearchUser", "PARAS", json);
		JSONObject result;
		try {
			result = httpPost(COMMAN_SERVER_URL, parameters, new JSONObject(json));

			return result;

		} catch (JSONException e) {
			// pass: protocol error
			e.printStackTrace();
			return null;
		}
	}

	/*package*/ 
	JSONObject getQuanziList(String json) {
		Param[] parameters = buildParameters("FUNC", "GetQuanziList", "PARAS", json);
		JSONObject result;
		try {
			result = httpPost(COMMAN_SERVER_URL, parameters, new JSONObject(json));

			return result;

		} catch (JSONException e) {
			// pass: protocol error
			e.printStackTrace();
			return null;
		}
	}


	/*package*/ 
	JSONObject loginLog(String json) {
		Param[] parameters = buildParameters("FUNC", "LoginLog", "PARAS", json);
		JSONObject result;
		try {
			result = httpPost(COMMAN_SERVER_URL, parameters, new JSONObject(json));

			return result;

		} catch (JSONException e) {
			// pass: protocol error
			e.printStackTrace();
			return null;
		}
	}


	/*package*/ 
	JSONObject getLevelList(String json) {
		Param[] parameters = buildParameters("FUNC", "GetLevelList", "PARAS", json);
		JSONObject result;
		try {
			result = httpPost(COMMAN_SERVER_URL, parameters, new JSONObject(json));

			return result;

		} catch (JSONException e) {
			// pass: protocol error
			e.printStackTrace();
			return null;
		}
	}

	/*package*/ 
	JSONObject getSuColorList(String json) {
		Param[] parameters = buildParameters("FUNC", "GetSuColorList", "PARAS", json);
		JSONObject result;
		try {
			result = httpPost(COMMAN_SERVER_URL, parameters, new JSONObject(json));

			return result;

		} catch (JSONException e) {
			// pass: protocol error
			e.printStackTrace();
			return null;
		}
	}

	/*package*/ 
	JSONObject addSharePinglun(String json) {
		Param[] parameters = buildParameters("FUNC", "AddSharePinglun", "PARAS", json);
		JSONObject result;
		try {
			result = httpPost(COMMAN_SERVER_URL, parameters, new JSONObject(json));

			return result;

		} catch (JSONException e) {
			// pass: protocol error
			e.printStackTrace();
			return null;
		}
	}
	/*package*/ 
	JSONObject checkRelation(String json) {
		Param[] parameters = buildParameters("FUNC", "CheckRelation", "PARAS", json);
		JSONObject result;
		try {
			result = httpPost(COMMAN_SERVER_URL, parameters, new JSONObject(json));

			return result;

		} catch (JSONException e) {
			// pass: protocol error
			e.printStackTrace();
			return null;
		}
	}

	/*package*/ 
	JSONObject getShareListNew(String json) {
		Param[] parameters = buildParameters("FUNC", "GetShareListNew", "PARAS", json);
		JSONObject result;
		try {
			result = httpPost(COMMAN_SERVER_URL, parameters, new JSONObject(json));

			return result;

		} catch (JSONException e) {
			// pass: protocol error
			e.printStackTrace();
			return null;
		}
	}




	JSONObject changeRelation( int userid,  int friendid,  int i_relation, String json) {
		Param[] parameters = buildParameters("userid", userid + "", "friendid", friendid + "", "relation", i_relation + "");

		JSONObject result;
		result = httpPost(GetShareListNewBase + "relation/changeRelation", parameters,  json);

		return result;

	}

	JSONObject getUserLogin2( String phone,  String pass, String json) {
		//		Param[] parameters = buildParameters("i_phone", phone + "", "pass", pass + "");
		Param[] parameters = buildParameters("FUNC", "UserLogin2", "PARAS", json);
		JSONObject result;
		result = httpPost(COMMAN_SERVER_URL, parameters,  json);

		return result;

	}




	/*package*/ 
	JSONObject GetShareListNewURL( int userid,  int typeid,  int zannum,  int plnum,  int pagenum, String json) {
		Param[] parameters = buildParameters("pagenum", pagenum + "", "userid", userid + "", "zannum", zannum + "", "plnum", plnum + "", "typeid",typeid + "");

		JSONObject result;
		result = httpPost(GetShareListNewURL, parameters,  json);

		return result;

	}

	/*package*/ 
	JSONObject getAllCount( int i_userid , String json) {
		Param[] parameters = buildParameters("userid", i_userid + "");

		JSONObject result;
		result = httpPost(GetShareListNewBase + "/user/getAllCount", parameters,  json);

		return result;

	}


	/*package*/ 
	JSONObject getFriendDetailNew( int i_userid ,  int i_friendid , String json) {
		Param[] parameters = buildParameters("userid", i_userid + "", "friendid", i_friendid + "");

		JSONObject result;
		result = httpPost(GetShareListNewBase + "friend/getFriendDetailNew", parameters,  json);

		return result;

	}

	/*package*/ 
	JSONObject getSysAd(String json) {
		Param[] parameters = buildParameters("FUNC", "GetSysAd", "PARAS", json);
		JSONObject result;
		try {
			result = httpPost(COMMAN_SERVER_URL, parameters, new JSONObject(json));

			return result;

		} catch (JSONException e) {
			// pass: protocol error
			e.printStackTrace();
			return null;
		}
	}



	/*package*/ 
	JSONObject addFollower(String json) {
		Param[] parameters = buildParameters("FUNC", "AddFollower", "PARAS", json);
		JSONObject result;
		try {
			result = httpPost(COMMAN_SERVER_URL, parameters, new JSONObject(json));

			return result;

		} catch (JSONException e) {
			// pass: protocol error
			e.printStackTrace();
			return null;
		}
	}

	/*package*/ 
	JSONObject addGuanzhu(String json) {
		Param[] parameters = buildParameters("FUNC", "AddGuanzhu", "PARAS", json);
		JSONObject result;
		try {
			result = httpPost(COMMAN_SERVER_URL, parameters, new JSONObject(json));

			return result;

		} catch (JSONException e) {
			// pass: protocol error
			e.printStackTrace();
			return null;
		}
	}

	/*package*/ 
	JSONObject addFriendApp(String json) {
		Param[] parameters = buildParameters("FUNC", "AddFriendApy", "PARAS", json);
		JSONObject result;
		try {
			result = httpPost(COMMAN_SERVER_URL, parameters, new JSONObject(json));

			return result;

		} catch (JSONException e) {
			// pass: protocol error
			e.printStackTrace();
			return null;
		}
	}

	/*package*/ 
	JSONObject AddFriendSweep(String i_userid, String i_friendid) {
		Param[] parameters = buildParameters("i_userid", i_userid, "i_friendid", i_friendid);
		JSONObject result;
		result = httpPost(GetShareListNewBase + "Friend/AddFriendSweep", parameters, "");

		return result;
	}	

	/*package*/ 
	JSONObject setShareState(String i_userid, String i_friendid, String i_sta) {
		Param[] parameters = buildParameters("i_userid", i_userid, "i_friendid", i_friendid, "i_sta", i_sta);
		JSONObject result;
		result = httpPost(GetShareListNewBase + "Share/SetShareState", parameters, "");

		return result;
	}	

	/*package*/ 
	JSONObject setShareStateUser(String i_userid, String i_friendid, String i_sta) {
		Param[] parameters = buildParameters("i_userid", i_userid, "i_friendid", i_friendid, "i_sta", i_sta);
		JSONObject result;
		result = httpPost(GetShareListNewBase + "Share/SetShareStateUser", parameters, "");

		return result;
	}	

	/*package*/ 
	JSONObject setFriendState(String i_userid, String i_friendid, String i_sta) {
		Param[] parameters = buildParameters("i_userid", i_userid, "i_friendid", i_friendid, "i_sta", i_sta);
		JSONObject result;
		result = httpPost(GetShareListNewBase + "Friend/SetFriendState", parameters, "");

		return result;
	}	

	JSONObject friendGetSearchDetail(String i_userid, String i_shareid, String i_content,String i_lat, String i_lng, String i_replyid) {
		Param[] parameters = buildParameters("i_userid", i_userid, "i_shareid", i_shareid, "i_content", i_content  , "i_lat", i_lat, "i_lng", i_lng, "i_replyid", i_replyid);
		JSONObject result;
		result = httpPost(GetShareListNewBase + "FriendGetSearchDetail", parameters, "");

		return result;

	}

	JSONObject setPinglunReply(String i_userid, String i_shareid, String i_content,String i_lat, String i_lng, String i_replyid) {
		Param[] parameters = buildParameters("i_userid", i_userid, "i_shareid", i_shareid, "i_content", i_content  , "i_lat", i_lat, "i_lng", i_lng, "i_replyid", i_replyid);
		JSONObject result;
		result = httpPost(GetShareListNewBase + "Share/SetCommentReply", parameters, "");

		return result;

	}


	/*package*/ 
	JSONObject getSearchFriend(String i_userid, String i_key, String i_page, String i_size) {
		Param[] parameters = buildParameters("i_userid", i_userid, "i_key", i_key, "i_page", i_page, "i_size", i_size);
		JSONObject result;
		result = httpPost(GetShareListNewBase + "Friend/GetSearchFriend", parameters, "");

		return result;
	}	

	/*package*/ 
	JSONObject SetStore(String userid, String shareid) {
		Param[] parameters = buildParameters("i_userid", userid, "i_shareid", shareid);
		JSONObject result;
		result = httpPost(GetShareListNewBase + "Share/SetStore", parameters, "");

		return result;
	}	

	/*package*/ 
	JSONObject GetStore(String userid, String i_num, String i_page) {
		Param[] parameters = buildParameters("i_userid", userid,"i_num", i_num,"i_page", i_page);
		JSONObject result;
		result = httpPost(GetShareListNewBase + "Share/GetStore", parameters, "");

		return result;
	}	

	/*package*/ 
	JSONObject getVoidObject(String userid, String vo_id) {
		Param[] parameters = buildParameters("vo_id", vo_id, "i_userid", userid);
		JSONObject result;
		result = httpPost(GetShareListNewBase + "Friend/GetVoidObject", parameters, "");

		return result;
	}	

	/*package*/ 
	JSONObject acceptFriendApy(String json) {
		Param[] parameters = buildParameters("FUNC", "AcceptFriendApy", "PARAS", json);
		JSONObject result;
		try {
			result = httpPost(COMMAN_SERVER_URL, parameters, new JSONObject(json));

			return result;

		} catch (JSONException e) {
			// pass: protocol error
			e.printStackTrace();
			return null;
		}
	}	

	/*package*/ 
	JSONObject getFriendApyList(String json) {
		Param[] parameters = buildParameters("FUNC", "GetFriendApyList", "PARAS", json);
		JSONObject result;
		try {
			result = httpPost(COMMAN_SERVER_URL, parameters, new JSONObject(json));

			return result;

		} catch (JSONException e) {
			// pass: protocol error
			e.printStackTrace();
			return null;
		}
	}	

	/*package*/ 
	JSONObject GetEnSuperChatList(String json) {
		Param[] parameters = buildParameters("FUNC", "GetEnSuperChatList", "PARAS", json);
		JSONObject result;
		try {
			result = httpPost(COMMAN_SERVER_URL, parameters, new JSONObject(json));

			return result;

		} catch (JSONException e) {
			// pass: protocol error
			e.printStackTrace();
			return null;
		}
	}


	/*package*/ 
	JSONObject getNearUserList(String json) {
		Param[] parameters = buildParameters("FUNC", "GetNearUserList", "PARAS", json);
		JSONObject result;
		try {
			result = httpPost(COMMAN_SERVER_URL, parameters, new JSONObject(json));

			return result;

		} catch (JSONException e) {
			// pass: protocol error
			e.printStackTrace();
			return null;
		}
	}

	/*package*/ 
	JSONObject getFriendList(String json) {
		Param[] parameters = buildParameters("FUNC", "GetFriendList", "PARAS", json);
		JSONObject result;
		try {
			result = httpPost(COMMAN_SERVER_URL, parameters, new JSONObject(json));

			return result;

		} catch (JSONException e) {
			// pass: protocol error
			e.printStackTrace();
			return null;
		}
	}



	/*package*/ 
	JSONObject getEnSuperChatList(String json) {
		Param[] parameters = buildParameters("FUNC", "getEnSuperChatList", "PARAS", json);
		JSONObject result;
		try {
			result = httpPost(COMMAN_SERVER_URL, parameters, new JSONObject(json));

			return result;

		} catch (JSONException e) {
			// pass: protocol error
			e.printStackTrace();
			return null;
		}
	}


	/*package*/ 
	JSONObject getCallHistory(String json) {
		Param[] parameters = buildParameters("FUNC", "GetCallHistory2", "PARAS", json);
		JSONObject result;
		try {
			result = httpPost(COMMAN_SERVER_URL, parameters, new JSONObject(json));

			return result;

		} catch (JSONException e) {
			// pass: protocol error
			e.printStackTrace();
			return null;
		}
	}




	/*package*/ 
	JSONObject getGuanzhuList(String json) {
		Param[] parameters = buildParameters("FUNC", "GetGuanzhuList", "PARAS", json);
		JSONObject result;
		try {
			result = httpPost(COMMAN_SERVER_URL, parameters, new JSONObject(json));

			return result;

		} catch (JSONException e) {
			// pass: protocol error
			e.printStackTrace();
			return null;
		}
	}

	/*package*/ 
	JSONObject getFensiList(String json) {
		Param[] parameters = buildParameters("FUNC", "GetFensiList", "PARAS", json);
		JSONObject result;
		try {
			result = httpPost(COMMAN_SERVER_URL, parameters, new JSONObject(json));

			return result;

		} catch (JSONException e) {
			// pass: protocol error
			e.printStackTrace();
			return null;
		}
	}
	/*package*/ 
	JSONObject addShareZan(String json) {
		Param[] parameters = buildParameters("FUNC", "AddShareZan", "PARAS", json);
		JSONObject result;
		try {
			result = httpPost(COMMAN_SERVER_URL, parameters, new JSONObject(json));

			return result;

		} catch (JSONException e) {
			// pass: protocol error
			e.printStackTrace();
			return null;
		}
	}


	/*package*/ 
	JSONObject getShareList(String json) {
		Param[] parameters = buildParameters("FUNC", "GetShareList3", "PARAS", json);
		JSONObject result;
		try {
			result = httpPost(COMMAN_SERVER_URL, parameters, new JSONObject(json));

			return result;

		} catch (JSONException e) {
			// pass: protocol error
			e.printStackTrace();
			return null;
		}
	}

	/*package*/ 
	JSONObject SendPushMsg(String json) {
		Param[] parameters = buildParameters("FUNC", "SendPushMsg", "PARAS", json);
		JSONObject result;
		try {
			result = httpPost(NORMAL_SERVER_URL + "SendPushMsg", parameters, new JSONObject(json));

			return result;

		} catch (JSONException e) {
			// pass: protocol error
			e.printStackTrace();
			return null;
		}
	}


	/*package*/ 
	JSONObject SendPushMsg2(String json) {
		Param[] parameters = buildParameters("FUNC", "SendPushMsg", "PARAS", json);
		JSONObject result;
		try {
			result = httpPost(NORMAL_SERVER_URL + "/SendPushMsg", parameters, new JSONObject(json));

			return result;

		} catch (JSONException e) {
			// pass: protocol error
			e.printStackTrace();
			return null;
		}
	}

	/* 0: success, 1: login unavailable, 2: io erro
	/*package*/ 
	JSONObject setCreateCallRecord(final String i_userid ,final String i_otherid) {
		Param[] parameters = buildParameters("i_userid", i_userid + "",  "i_otherid", i_otherid + "");
		JSONObject result;
		result = httpPost(SERVER_URL + "User/SetCreateCallRecord", parameters, "{}");
		if(result != null ) {
			return result;
		} else {
			return null;
		}
	}
	
	

	/* 0: success, 1: login unavailable, 2: io erro
	/*package*/ 
	JSONObject setUpdateCallRecord(final int i_callid ,final int i_userid) {
		Param[] parameters = buildParameters("i_callid", i_callid + "",  "i_userid", i_userid + "");
		JSONObject result;
		result = httpPost(SERVER_URL + "User/SetUpdateCallRecord", parameters, "{}");
		if(result != null ) {
			return result;
		} else {
			return null;
		}
	}
	
	/* 0: success, 1: login unavailable, 2: io erro
	/*package*/ 
	JSONObject getOtherCounter(final int i_callid ,final int i_userid) {
		Param[] parameters = buildParameters("i_callid", i_callid + "",  "i_userid", i_userid + "");
		JSONObject result;
		result = httpPost(SERVER_URL + "User/GetOtherCounter", parameters, "{}");
		if(result != null ) {
			return result;
		} else {
			return null;
		}
	}


	/* 0: success, 1: login unavailable, 2: io erro
	/*package*/ 
	JSONObject getCallRecord(final String i_otherid) {
		Param[] parameters = buildParameters("i_otherid", i_otherid + "");
		JSONObject result;
		result = httpPost(SERVER_URL + "User/GetCallRecord", parameters, "{}");
		if(result != null ) {
			return result;
		} else {
			return null;
		}
	}

	/* 0: success, 1: login unavailable, 2: io erro
	/*package*/ 
	JSONObject setOverCallRecord(final String i_callid) {
		Param[] parameters = buildParameters("i_callid", i_callid + "");
		JSONObject result;
		result = httpPost(SERVER_URL + "User/SetOverCallRecord", parameters, "{}");
		if(result != null ) {
			return result;
		} else {
			return null;
		}
	}
	/* 0: success, 1: login unavailable, 2: io erro
	/*package*/ 
	JSONObject getRegisterData() {
		Param[] parameters = buildParameters();
		JSONObject result;
		result = httpGet("http://www.dadapicture.com/uploadimg/dataregister.php",parameters);

		if(result != null ) {
			return result;
		} else {
			return null;
		}
	}


	/* 0: success, 1: login unavailable, 2: io erro


	
	/* 0: success, 1: login unavailable, 2: io erro
	/*package*/ 
	JSONObject setUpdateCallRecord(final String i_callid ,final int i_userid) {
		Param[] parameters = buildParameters("i_callid", i_callid + "",  "i_userid", i_userid + "");
		JSONObject result;
		result = httpPost(SERVER_URL + "User/SetUpdateCallRecord", parameters, "{}");
		if(result != null ) {
			return result;
		} else {
			return null;
		}
	}
	

	
	/* 0: success, 1: login unavailable, 2: io erro
	/*package*/ 
	JSONObject SendPushMsg(final String content ,final int MsgType, final String ToUserPhone,  final String AlertMsg, final String json) {
		Param[] parameters = buildParameters("MsgType", MsgType + "",  "AlertMsg", AlertMsg,  "ToUserPhone", ToUserPhone,  "MsgData", content);
		JSONObject result;
		try {
			//result = httpPost(GetShareListNewBase + "push/sendAlert", parameters, new JSONObject(json));
			result = httpPost(SERVER_URL + "Super/SendPushMsg2", parameters, new JSONObject(json));
			if(result != null ) {
				return result;
			} else {
				return null;
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}


	/* 0: success, 1: login unavailable, 2: io erro
	/*package*/ 
	JSONObject requestReason(String reason, String userid, String requestuserid, String pageindex, String pagesize) {
		Param[] parameters = buildParameters(ACK, "requestReason",  "reason", reason,  "userid", userid,"requestuserid", requestuserid);
		JSONObject result;
		result = httpGet(Parameters.BASEINDEX + "/phone/Friend.html",parameters);

		if(result != null ) {
			return result;
		} else {
			return null;
		}

	}

	/* 0: success, 1: login unavailable, 2: io erro
	/*package*/ 
	JSONObject updatefriendstatus(String reason, String notificationid, String status, String pageindex, String pagesize) {
		Param[] parameters = buildParameters(ACK, "updatefriendstatus",  "reason", reason,  "notificationid", notificationid,"status", status);
		JSONObject result;
		result = httpGet(Parameters.BASEINDEX + "/phone/Friend.html",parameters);

		if(result != null ) {
			return result;
		} else {
			return null;
		}

	}



	/*package*/ 
	JSONObject updatefirendnotificationnew(String userid, String pageindex, String pagesize) {
		Param[] parameters = buildParameters(ACK, "updatefirendnotificationnew",  "userid", userid);
		JSONObject result;
		result = httpGet(Parameters.BASEINDEX + "/phone/Friend.html",parameters);

		if(result != null ) {
			return result;
		} else {
			return null;
		}

	}

	/** A convenience method to build an array of parameters from a list of strings */
	/*package*/ Param[] buildParameters(String... name_value_pairs) {
		int l = name_value_pairs.length/2;
		Param[] params;
		int next;
		if(mToken != null) {
			l++;
			params = new Param[l];
			params[0] = new Param(TOKEN, mToken);
			next = 1;
		} else {
			params = new Param[l];
			next =0;
		}


		int nv=0;
		for(; next<l; next++) {
			String name = name_value_pairs[nv++];
			String value = name_value_pairs[nv++];
			params[next] = new Param(name, value);
		}

		return params;
	}


	private JSONObject httpQuery(HttpVerb verb, Param[] parameters, JSONObject input) {
		/*if(parameters.length>0 && !parameters[0].first.equals(TOKEN) && !action.equals(ACTION_AUTHENTICATE) && !action.equals(ACTION_SIGNUP)) {
			authenticate(mSession.getLogin(), mSession.getPassword());
			if(mToken != null){
				Log.i("token est null", action);
				Param[] newParameters = new Param[parameters.length + 1];
				newParameters[0] = new Param(TOKEN, mToken);
				for(int i = 0; i<parameters.length ; i++) {
					newParameters[i + 1] = parameters[i];
				}
			}
		}*/
		JSONObject reply = null;

		HttpURLConnection con = null;
		InputStream http_is = null;
		OutputStream http_os = null;
		BufferedReader br = null;
		StringBuilder sb = null;

		try {
			String target = buildRequestTarget(parameters);
			if(Parameters.DEBUG) {
				// ready to paste command line because providing test cases for bugs in web services is the most frequent operation
				String cmd = "curl --request "+verb;

				if(input != null) {
					cmd+=" --data '"+input.toString()+"'";
				}
				cmd+=" '"+target+"'";
				Log.i(TAG, cmd);
			}
			URL url = new URL(target);
			con = (HttpURLConnection)url.openConnection();

			con.setConnectTimeout(CONNECTION_TIMEOUT);
			con.setReadTimeout(READ_TIMEOUT);

			con.setRequestMethod(verb.toString());

			con.setDoInput(true);

			if(verb == HttpVerb.POST) {
				con.setDoOutput(true);

				http_os = con.getOutputStream();
				http_os.write(input.toString().getBytes("utf8"));
				http_os.close();
			}

			http_is = con.getInputStream();
			//	        http_is = url.openStream();
			br = new BufferedReader(new InputStreamReader(http_is, "utf8"), 32768);

			String line;
			sb = new StringBuilder(32768);
			while((line=br.readLine()) != null) {
				sb.append(line);
			}

			// encapsulate arrays
			if(sb.length()>0 && sb.charAt(0)=='[') {
				sb.insert(0, "{ \""+ITEMS+"\":");
				sb.append('}');
			}

			reply = new JSONObject(sb.toString());
		} catch (IOException e) {
			if(Parameters.DEBUG) {
				Log.i(TAG, sb!=null ? sb.toString() : "<no data>");
				e.printStackTrace();
			}


			//Loose connection
			if(!isNetworkAvailable() && first){

				mHandler.post(new Runnable() {
					@Override
					public void run() {
						Toast.makeText(mContext, "没有网络", Toast.LENGTH_SHORT).show();
						first = false;
					}
				});

			}

			//Refetch connection 
			if(isNetworkAvailable() && !first){

				mHandler.post(new Runnable() {
					@Override
					public void run() {

						Toast.makeText(mContext, "连入网络", Toast.LENGTH_SHORT).show();
						first = true;

					}
				});


			}

		} catch (JSONException e) {
			e.printStackTrace();
			return null;
		} finally {
			try { if(con != null) con.disconnect(); } catch(Exception e) {}
			try { if(br != null) br.close(); } catch(Exception e) {}
			try { if(http_os != null) http_os.close(); } catch(Exception e) {}
			try { if(http_is != null) http_is.close(); } catch(Exception e) {}
		}


		//If session is in mode connected and there is no response of the server : pass in mode disconnect
		if(reply == null && mSession.isConnected()) {
			mSession.setConnected(false);
			Log.i("reply", "null");
		}

		return reply;
	}

	private JSONObject httpQuery(HttpVerb verb, Param[] parameters, JSONObject input, String baseurl) {
		/*if(parameters.length>0 && !parameters[0].first.equals(TOKEN) && !action.equals(ACTION_AUTHENTICATE) && !action.equals(ACTION_SIGNUP)) {
			authenticate(mSession.getLogin(), mSession.getPassword());
			if(mToken != null){
				Log.i("token est null", action);
				Param[] newParameters = new Param[parameters.length + 1];
				newParameters[0] = new Param(TOKEN, mToken);
				for(int i = 0; i<parameters.length ; i++) {
					newParameters[i + 1] = parameters[i];
				}
			}
		}*/
		JSONObject reply = null;

		HttpURLConnection con = null;
		InputStream http_is = null;
		OutputStream http_os = null;
		BufferedReader br = null;
		StringBuilder sb = null;

		try {
			String target = buildRequestTarget(baseurl, parameters);
			if(Parameters.DEBUG) {
				// ready to paste command line because providing test cases for bugs in web services is the most frequent operation
				String cmd = "curl --request "+verb;

				if(input != null) {
					cmd+=" --data '"+input.toString()+"'";
				}
				cmd+=" '"+target+"'";
				Log.i(TAG, cmd);
			}
			URL url = new URL(target);
			con = (HttpURLConnection)url.openConnection();

			con.setConnectTimeout(CONNECTION_TIMEOUT);
			con.setReadTimeout(READ_TIMEOUT);

			con.setRequestMethod(verb.toString());

			con.setDoInput(true);

			if(verb == HttpVerb.POST) {

				//				 PrintWriter pw = new PrintWriter(con.getOutputStream());
				//				                      pw.print(parameters);
				//				                       pw.flush();
				//				                       pw.close();

				String params = buildRequestTargetPost(parameters);
				Log.i("url", url + "");
				Log.i("params", params + "");
				con.setDoOutput(true);

				http_os = con.getOutputStream();
				http_os.write(params.getBytes("utf8"));
				http_os.close();
			}

			http_is = con.getInputStream();
			//	        http_is = url.openStream();
			br = new BufferedReader(new InputStreamReader(http_is, "utf8"), 32768);

			String line;
			sb = new StringBuilder(32768);
			int cpt = 0;
			while((line=br.readLine()) != null) {
				sb.append(line);
				Log.i("cpt", cpt + "" + line);
				cpt ++ ;
			}

			// encapsulate arrays
			if(sb.length()>0 && sb.charAt(0)=='[') {
				sb.insert(0, "{ \""+ITEMS+"\":");
				sb.append('}');
			}
			String replyString = sb.toString();
			replyString = removeBOM(replyString);
			replyString = replyString.replace("\"{", "{");
			replyString = replyString.replace("}\"", "}");
			replyString = replyString.replace("\\", "");
			reply = new JSONObject(replyString);
		} catch (IOException e) {
			if(Parameters.DEBUG) {
				Log.i(TAG, sb!=null ? sb.toString() : "<no data>");
				e.printStackTrace();
			}


			//Loose connection
			if(!isNetworkAvailable() && first){

				mHandler.post(new Runnable() {
					@Override
					public void run() {
						Toast.makeText(mContext, "没有网络", Toast.LENGTH_SHORT).show();
						first = false;
					}
				});

			}

			//Refetch connection 
			if(isNetworkAvailable() && !first){

				mHandler.post(new Runnable() {
					@Override
					public void run() {

						Toast.makeText(mContext, "连入网络", Toast.LENGTH_SHORT).show();
						first = true;

					}
				});


			}

		} catch (JSONException e) {
			e.printStackTrace();
			Log.i("info", e.getMessage());
			return null;
		} finally {
			try { if(con != null) con.disconnect(); } catch(Exception e) {}
			try { if(br != null) br.close(); } catch(Exception e) {}
			try { if(http_os != null) http_os.close(); } catch(Exception e) {}
			try { if(http_is != null) http_is.close(); } catch(Exception e) {}
		}


		//If session is in mode connected and there is no response of the server : pass in mode disconnect
		if(reply == null && mSession.isConnected()) {
			mSession.setConnected(false);
			Log.i("reply", "null");
		}

		return reply;
	}

	private JSONObject httpQuery(HttpVerb verb, Param[] parameters, String input, String baseurl) {
		/*if(parameters.length>0 && !parameters[0].first.equals(TOKEN) && !action.equals(ACTION_AUTHENTICATE) && !action.equals(ACTION_SIGNUP)) {
			authenticate(mSession.getLogin(), mSession.getPassword());
			if(mToken != null){
				Log.i("token est null", action);
				Param[] newParameters = new Param[parameters.length + 1];
				newParameters[0] = new Param(TOKEN, mToken);
				for(int i = 0; i<parameters.length ; i++) {
					newParameters[i + 1] = parameters[i];
				}
			}
		}*/
		JSONObject reply = null;

		HttpURLConnection con = null;
		InputStream http_is = null;
		OutputStream http_os = null;
		BufferedReader br = null;
		StringBuilder sb = null;

		try {
			String target = buildRequestTarget(baseurl, parameters);
			if(Parameters.DEBUG) {
				// ready to paste command line because providing test cases for bugs in web services is the most frequent operation
				String cmd = "curl --request "+verb;

				if(input != null) {
					cmd+=" --data '"+input.toString()+"'";
				}
				cmd+=" '"+target+"'";
				Log.i(TAG, cmd);
			}
			URL url = new URL(target);
			con = (HttpURLConnection)url.openConnection();

			con.setConnectTimeout(CONNECTION_TIMEOUT);
			con.setReadTimeout(READ_TIMEOUT);

			con.setRequestMethod(verb.toString());

			con.setDoInput(true);

			if(verb == HttpVerb.POST) {

				//				 PrintWriter pw = new PrintWriter(con.getOutputStream());
				//				                      pw.print(parameters);
				//				                       pw.flush();
				//				                       pw.close();

				String params = buildRequestTargetPost(parameters);

				con.setDoOutput(true);

				http_os = con.getOutputStream();
				http_os.write(params.getBytes("utf8"));
				http_os.close();
			}

			http_is = con.getInputStream();
			//	        http_is = url.openStream();
			br = new BufferedReader(new InputStreamReader(http_is, "utf8"), 32768);

			String line;
			sb = new StringBuilder(32768);
			while((line=br.readLine()) != null) {
				sb.append(line);
			}

			// encapsulate arrays
			if(sb.length()>0 && sb.charAt(0)=='[') {
				sb.insert(0, "{ \""+ITEMS+"\":");
				sb.append('}');
			}
			String replyString = sb.toString();
			replyString = removeBOM(replyString);
			reply = new JSONObject(replyString);
		} catch (IOException e) {
			if(Parameters.DEBUG) {
				Log.i(TAG, sb!=null ? sb.toString() : "<no data>");
				e.printStackTrace();
			}


			//Loose connection
			if(!isNetworkAvailable() && first){

				mHandler.post(new Runnable() {
					@Override
					public void run() {
						Toast.makeText(mContext, "没有网络", Toast.LENGTH_SHORT).show();
						first = false;
					}
				});

			}

			//Refetch connection 
			if(isNetworkAvailable() && !first){

				mHandler.post(new Runnable() {
					@Override
					public void run() {

						Toast.makeText(mContext, "连入网络", Toast.LENGTH_SHORT).show();
						first = true;

					}
				});


			}

		} catch (JSONException e) {
			e.printStackTrace();
			Log.i("info", e.getMessage());
			return null;
		} finally {
			try { if(con != null) con.disconnect(); } catch(Exception e) {}
			try { if(br != null) br.close(); } catch(Exception e) {}
			try { if(http_os != null) http_os.close(); } catch(Exception e) {}
			try { if(http_is != null) http_is.close(); } catch(Exception e) {}
		}


		//If session is in mode connected and there is no response of the server : pass in mode disconnect
		if(reply == null && mSession.isConnected()) {
			mSession.setConnected(false);
			Log.i("reply", "null");
		}

		return reply;
	}


	public static final String removeBOM(String data) {
		if (TextUtils.isEmpty(data)) {
			return data;
		}

		if (data.startsWith("\ufeff")) {
			return data.substring(1);
		} else {
			return data;
		}
	}

	private String buildRequestTarget( Param[] parameters) {
		StringBuffer target = new StringBuffer(500);
		target.append(mDevMode ? Parameters.SERVER_URL_DEV : Parameters.SERVER_URL_PROD);
		//		target.append(action);
		if(parameters!=null && parameters.length>0) {
			char sep='?';
			for(Param p : parameters) {
				target.append(sep);
				target.append(URLEncoder.encode(p.first.toString()));
				target.append('=');
				target.append(URLEncoder.encode(p.second.toString()));
				sep='&';
			}
		}

		return target.toString();
	}

	private String buildRequestTarget( String url,  Param[] parameters) {
		StringBuffer target = new StringBuffer(500);
		target.append(url);
		//		target.append(action);
		if(parameters!=null && parameters.length>0) {
			char sep='?';

			for(Param p : parameters) {
				try {


					if(p != null) {
						target.append(sep);
						target.append(URLEncoder.encode(p.first.toString()));
						target.append('=');
						target.append(URLEncoder.encode(p.second.toString()));
						sep='&';
					}
				} catch(NullPointerException e) {

				}
			}
		}

		return target.toString();
	}


	private String buildRequestTargetPost( Param[] parameters) {
		StringBuffer target = new StringBuffer(500);
		//		target.append(action);
		if(parameters!=null && parameters.length>0) {
			//			char sep = ' ';
			for(Param p : parameters) {
				try {


					if(p != null) {
						target.append("&");
						target.append(URLEncoder.encode(p.first.toString()));
						target.append('=');
						target.append(URLEncoder.encode(p.second.toString()));
					}
				} catch(NullPointerException e) {

				}
			}
		}

		return target.toString();
	}



	//* 0: authenticated, 1: unauthorized, 2: io error
	/*package*/ JSONObject authenticate(String login, String password) {
		//		String action = IO.ACTION_AUTHENTICATE;
		Param[] parameters = buildParameters( ACK, "login" , "user", login, "password", password);

		JSONObject result;
		try {

			result = httpGet(parameters);
			//si j'ai un json en retour
			if(result != null ) {
				if(result.getInt("status")==1) {
					JSONObject mJSONObject = result.getJSONObject("data");
					mToken = mJSONObject.getString("UserCode");
				}
				return result;
			}

		} catch (JSONException e) {
			// pass: protocol error
			e.printStackTrace();
			return null;
		}
		return null;
	}



	//* 0: authenticated, 1: unauthorized, 2: io error
	/*package*/ JSONObject updateStatus(String groupuserid, String groupid, String userid, String grouprole) {
		//		String action = IO.ACTION_AUTHENTICATE;
		Param[] parameters = buildParameters( ACK, "setuserrole" , "groupuserid", groupuserid, "groupid", groupid, "userid", userid,"grouprole" ,grouprole);

		JSONObject result;

		result = httpGet(Parameters.BASEINDEX + "/phone/Group.html", parameters);
		if(result != null ) {
			return result;
		}

		return null;
	}

	JSONObject addActivityUserinfo( String activityid,  String userid,  String truename,  String contactway,  String emergencycontactname,  String emergencycontact,  String qq,  String remark,  String accoutercontent,  String experiencecontent,  String idcard) {
		Param[] parameters = buildParameters( ACK, "addactivityuserinfo" , "activityid", activityid, "userid", userid, "truename", truename,"contactway" ,contactway,"emergencycontactname" ,emergencycontactname,"emergencycontact" ,emergencycontact,"qq" ,qq,"remark" ,remark,"accoutercontent" ,accoutercontent,"experiencecontent" ,experiencecontent,"idcard" ,idcard);

		JSONObject result;

		result = httpGet(Parameters.BASEINDEX + "/phone/Activity.html", parameters);
		if(result != null ) {
			return result;
		}
		return null;

	}

	//* 0: authenticated, 1: unauthorized, 2: io error
	/*package*/ JSONObject getGroupList(String pageindex, String pageSize) {
		//		String action = IO.ACTION_AUTHENTICATE;
		Param[] parameters = buildParameters( ACK, "datagroup" , "pageindex", pageindex, "pagesize", "20", "userid", "1","order" ,"ug.id_DESC", "isall", "1");

		JSONObject result;

		result = httpGet(Parameters.BASEINDEX + "/phone/Group.html", parameters);
		//si j'ai un json en retour
		if(result != null ) {
			/*	if(result.getInt("status")==1) {
						JSONObject mJSONObject = result.getJSONObject("data");
						mToken = mJSONObject.getString("UserCode");
					}*/
			return result;
		}

		return null;
	}


	//* 0: authenticated, 1: unauthorized, 2: io error
	/*package*/ JSONObject getGroupListByLocation(String userId, String longitude, String latitude, String pageindex, String pageSize) {
		//		String action = IO.ACTION_AUTHENTICATE;
		Param[] parameters = buildParameters( ACK, "datagroupbylocation" ,"latitude", latitude, "longitude", longitude,  "pageindex", pageindex, "pagesize", "20", "userid", userId,"order" ,"ug.id_DESC", "isall", "1");

		JSONObject result;

		result = httpGet(Parameters.BASEINDEX + "/phone/Group.html", parameters);
		//si j'ai un json en retour
		if(result != null ) {
			/*	if(result.getInt("status")==1) {
							JSONObject mJSONObject = result.getJSONObject("data");
							mToken = mJSONObject.getString("UserCode");
						}*/
			return result;
		}

		return null;
	}


	/*package*/ 
	JSONObject getGroupDynamic(String userId, String pageindex, String pageSize) {
		//		String action = IO.ACTION_AUTHENTICATE;
		Param[] parameters = buildParameters( ACK, "datauserfirstcomment" , "pageindex", pageindex, "pagesize", "20", "userid", userId);

		JSONObject result;

		result = httpGet(Parameters.BASEINDEX + "/phone/UserChat.html", parameters);
		//si j'ai un json en retour
		if(result != null ) {
			/*	if(result.getInt("status")==1) {
							JSONObject mJSONObject = result.getJSONObject("data");
							mToken = mJSONObject.getString("UserCode");
						}*/
			return result;
		}

		return null;
	}


	//* 0: authenticated, 1: unauthorized, 2: io error
	/*package*/ JSONObject getPOIByUserIdList(String uid, String pageindex, String pageSize) {
		//		String action = IO.ACTION_AUTHENTICATE;
		Param[] parameters = buildParameters( ACK, "datapoibyuid" ,"userid", uid,  "pageindex", pageindex, "pagesize", "20");

		JSONObject result;

		result = httpGet(Parameters.BASEINDEX + "/phone/Poi.html", parameters);
		//si j'ai un json en retour
		if(result != null ) {
			/*	if(result.getInt("status")==1) {
								JSONObject mJSONObject = result.getJSONObject("data");
								mToken = mJSONObject.getString("UserCode");
							}*/
			return result;
		}

		return null;
	}


	//* 0: authenticated, 1: unauthorized, 2: io error
	/*package*/ JSONObject getTrackingLocation(String uid, String longitude, String latitude, String pageindex, String pageSize) {
		//		String action = IO.ACTION_AUTHENTICATE;
		Param[] parameters = buildParameters( ACK, "datatrackingpoilocation" ,"userid", uid, "longitude", longitude, "latitude", latitude, "pageindex", pageindex, "pagesize", "20");

		JSONObject result;

		result = httpGet(Parameters.BASEINDEX + "/phone/Poi.html", parameters);
		//si j'ai un json en retour
		if(result != null ) {
			/*	if(result.getInt("status")==1) {
								JSONObject mJSONObject = result.getJSONObject("data");
								mToken = mJSONObject.getString("UserCode");
							}*/
			return result;
		}

		return null;
	}


	//* 0: authenticated, 1: unauthorized, 2: io error
	/*package*/ JSONObject getTrackingByUserId(String uid, String pageindex, String pageSize) {
		//		String action = IO.ACTION_AUTHENTICATE;
		Param[] parameters = buildParameters( ACK, "datatrackingpoibyid" ,"uid", uid, "pageindex", pageindex, "pagesize", "20");

		JSONObject result;

		result = httpGet(Parameters.BASEINDEX + "/phone/Poi.html", parameters);
		//si j'ai un json en retour
		if(result != null ) {
			/*	if(result.getInt("status")==1) {
									JSONObject mJSONObject = result.getJSONObject("data");
									mToken = mJSONObject.getString("UserCode");
								}*/
			return result;
		}

		return null;
	}


	//* 0: authenticated, 1: unauthorized, 2: io error
	/*package*/ JSONObject getPOIByUserIdListLocation(String uid, String longitude, String latitude, String pageindex, String pageSize) {
		//		String action = IO.ACTION_AUTHENTICATE;
		Param[] parameters = buildParameters( ACK, "datapoilocation" ,"userid", uid, "longitude", longitude, "latitude", latitude, "pageindex", pageindex, "pagesize", "20");

		JSONObject result;

		result = httpGet(Parameters.BASEINDEX + "/phone/Poi.html", parameters);
		//si j'ai un json en retour
		if(result != null ) {
			/*	if(result.getInt("status")==1) {
								JSONObject mJSONObject = result.getJSONObject("data");
								mToken = mJSONObject.getString("UserCode");
							}*/
			return result;
		}

		return null;
	}






	private JSONObject httpGet( Param[] parameters){
		return httpQuery(HttpVerb.GET, parameters, null);
	}

	private JSONObject httpGet( String url, Param[] parameters){

		return null;
		//		return httpQuery(HttpVerb.GET, parameters, null, url);
	}

	private JSONObject httpPost(String url, Param[] parameters, JSONObject input) {
		return httpQuery(HttpVerb.POST, parameters, input, url);
	}

	private JSONObject httpPost(String url, Param[] parameters, String input) {
		return httpQuery(HttpVerb.POST, parameters, input, url);
	}

	private enum HttpVerb {
		GET,
		POST
	}

	String getToken() {
		return mToken;
	}



	private boolean isNetworkAvailable() {
		ConnectivityManager connectivityManager = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
		return activeNetworkInfo != null;
	}
}